package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private EmpService empService;
    /**
     * 分页查询班级列表
     *
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Clazz> clazzPage(String name,LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> page1 = new Page<>(page, pageSize);
        //动态分页查询条件
        lambdaQuery().like(name != null, Clazz::getName, name)
                .ge(begin != null, Clazz::getBeginDate, begin)
                .le(end != null, Clazz::getEndDate, end)
                .page(page1);
        //根据班主任id查询班主任姓名
        Set<Integer> masterIds = page1.getRecords().stream().map(Clazz::getMasterId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(masterIds)) {
            empService.getBaseMapper().selectBatchIds(masterIds).forEach(emp -> {
                page1.getRecords().forEach(clazz -> {
                    if (emp.getId().equals(clazz.getMasterId())) {
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }
        return new PageResult<>(page1.getTotal(), page1.getRecords());
    }
}
